<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

class UsersController extends AppController {

    var $name = 'Users';

    /**
     *  El AuthComponent proporciona la funcionalidad necesaria
     *  para el acceso (login), por lo que se puede dejar esta funci�n en blanco.
     */
    /* function admin_index() {
      $this->pageTitle = 'Entrada Administrador';
      $this->layout = "login";
      }
     */


    function send() {
        App::import('Vendor', 'ClassPhpmailer', array('file' => 'phpmailer/class.phpmailer.php'));
        $this->layout = "ajax";
        if (empty($this->data)) {
            
        } else {
            $this->User->recursive = 0;
            if ($users = $this->User->find('all', array('conditions' => array('User.email' => $this->data['User']['correo']), 'fields' => array('User.email', 'User.username', 'User.nombre', 'User.primer_apellido', 'User.segundo_apellido', 'User.id')))) {
                foreach ($users as $user) {
                    $this->User->create();
                    $this->User->id = $user['User']['id'];

                    //Generamos la nueva clave de forma aleatorea

                    $str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
                    $clave = "";
                    for ($i = 0; $i < 8; $i++) {
                        $clave .= substr($str, rand(0, 62), 1);
                    }

                    $this->data['User']['password'] = $this->Auth->password($clave);
                    if ($this->User->save($this->data)) {
                        $mail = new PHPMailer();

//Luego tenemos que iniciar la validación por SMTP: 
                        $mail->IsSMTP();
                        $mail->SMTPAuth = true;
                        $mail->Host = "ssl://smtp.gmail.com"; // SMTP a utilizar. Por ej. smtp.elserver.com 
                        $mail->Username = "sitrural@gmail.com"; // Correo completo a utilizar 
                        $mail->Password = "laropavieja.net.co"; // Contraseña 
                        $mail->Port = 465; // Puerto a utilizar 
//Con estas pocas líneas iniciamos una conexión con el SMTP. Lo que ahora deberíamos hacer, es configurar el mensaje a enviar, el //From, etc. 
                        $mail->From = "sitrural@gmail.com"; // Desde donde enviamos (Para mostrar) 
                        $mail->FromName = "Soporte aplicativo tierras";

//Estas dos líneas, cumplirían la función de encabezado (En mail() usado de esta forma: “From: Nombre <correo@dominio.com>”) de //correo. 
//$mail->AddAddress('wilavel@gmail.com');// Esta es la dirección a donde enviamos 
                        $mail->AddAddress($user['User']['email']);
                        $mail->IsHTML(true);
//$mail->IsHTML(true); // El correo se envía como HTML 
                        $mail->Subject = "Cambio de clave sitrural.org"; // Este es el titulo del email. 
                        $body = "Se ha cambiado exitosamente su clave,los datos de su cuenta son: <br>";
                        $body .= " <strong>Usuario: " . $user['User']['nombre'] . " " . $user['User']['primer_apellido'] . $user['User']['segundo_apellido'] . "</strong><br>";
                        $body .= " <strong>Username: " . $user['User']['username'] . "</strong><br>";
                        $body .= " <strong>Nueva Clave: " . $clave . "</strong><br>";
                        $mail->Body = $body; // Mensaje a enviar 
//$mail->SMTPDebug = 1;

                        $exito = $mail->Send(); // Envía el correo. 
//También podríamos agregar simples verificaciones para saber si se envió: 
                        if ($exito) {
                            $this->Session->setFlash("Sus datos fueron enviados al correo  " . $user['User']['email']);
                        } else {
                            $this->Session->setFlash("Error :  " . $user['User']['email'] . " " . $mail->ErrorInfo);
                        }
                        $this->redirect(array('controller' => 'Users', 'action' => "send"));
                    } else {
                        $this->Session->setFlash("Error Guardando Datos");
                    }
                }
            } else {
                $this->Session->setFlash("No existe un usuario asociado a este correo");
            }
        }
    }

    function login() {
        $this->pageTitle = 'Inicio';
        $this->layout = "login";
    }

    function admin_login() {
        $this->layout = "login";
    }

    function logout() {
        $this->Session->setFlash('Su sesion ha expirado.');
        $this->Session->write('proy_id', "");
        $this->Session->write('cod', "");
        $this->redirect($this->Auth->logout());
        $this->Session->destroy();
    }

    function admin_logout() {
        $this->Session->setFlash('Su sesion ha expirado.');
        $this->Session->write('proy_id', "");
        $this->redirect($this->Auth->logout());
    }

    function admin_index() {
        if ($this->RequestHandler->isAjax())
            $this->layout = 'ajax';
        else {
            $this->layout = 'default';
        }
        $this->User->recursive = 0;
        $this->set('User', $this->User->find('all', array('fields' => array('User.username', 'User.id', 'User.email', 'User.primer_apellido', 'User.nombre', 'Branch.nombre', 'Group.name'))));
    }

    function admin_edit($id = null) {

        if (empty($this->data)) {


            //$this->data = $this->User->findById($id);
            $this->data = $this->User->find("first", array("conditions" => array("User.id" => $id)));
            $this->set('groups', $this->User->Group->find('list', array('order' => 'name ASC')));
            $this->set('branches', $this->User->Branch->find('list', array('order' => 'nombre ASC', 'fields' => array('id', 'nombre'))));
        } else {
            if ($this->User->save($this->data)) {

                $this->Session->setFlash("Usuario editado con exito");
                $this->redirect(array('controller' => 'users', 'action' => "index"));
            } else {
                $this->Session->setFlash("Error Guardando Datos");
                $this->set('groups', $this->User->Group->find('list', array('order' => 'name ASC')));
                $this->set('branches', $this->User->Branch->find('list', array('order' => 'nombre ASC', 'fields' => array('id', 'nombre'))));
            }
        }
    }

    function edit_user() {
        if (empty($this->data)) {

            $id = $this->Auth->user('id');
            //$this->data = $this->User->findById($id);
            $this->data = $this->User->find("first", array("conditions" => array("User.id" => $id)));
        } else {

            if ($this->Auth->password($this->data['User']['password']) != $this->Auth->password($this->data['User']['password_confirm'])) {
                $this->set('branches', $this->User->Branch->find('list', array('order' => 'nombre ASC', 'fields' => array('id', 'nombre'))));
                $this->set('groups', $this->User->Group->find('list', array('order' => 'name ASC')));
                echo "<script>alert('Las contraseñas no coinciden')</script>";
            } else {
                $this->data['User']['password'] = $this->Auth->password($this->data['User']['password']);
                if ($this->User->save($this->data)) {

                    $this->Session->setFlash("Usuario editado con exito");
                    $this->redirect(array('controller' => 'Pages', 'action' => "display"));
                } else {
                    $this->Session->setFlash("Error Guardando Datos");
                }
            }
        }
    }

    function admin_add() {
        $this->layout = "ajax";
        if (!empty($this->data)) {

            if ($this->data['User']['password'] != $this->Auth->password($this->data['User']['password_confirm'])) {
                $this->set('branches', $this->User->Branch->find('list', array('order' => 'nombre ASC', 'fields' => array('id', 'nombre'))));
                $this->set('groups', $this->User->Group->find('list', array('order' => 'name ASC')));
                echo "<script>alert('Las contraseñas no coinciden')</script>";
            } else {

                if ($this->User->saveAll($this->data)) {
                    $this->Session->setFlash("Usuario creado con exito");
                    $this->redirect(array("controller" => 'users', 'action' => 'index'));
                } else {
                    $this->Session->setFlash("Error guardando datos");
                    $this->set('branches', $this->User->Branch->find('list', array('order' => 'nombre ASC', 'fields' => array('id', 'nombre'))));
                    $this->set('groups', $this->User->Group->find('list', array('order' => 'name ASC')));
                }
            }
        } else {

            $this->set('branches', $this->User->Branch->find('list', array('order' => 'nombre ASC', 'fields' => array('id', 'nombre'))));
            $this->set('groups', $this->User->Group->find('list', array('order' => 'name ASC')));
        }
    }

    function admin_delete($id) {

        if ($this->User->delete($id)) {
            $this->Session->setFlash('Usuario Borrado con exito');
            $this->redirect(array('controller' => 'Users', 'action' => 'index'));
        }
    }

    function add_users() {
        $this->layout = "ajax";
        if (!empty($this->data)) {

            if ($this->data['User']['password'] != $this->Auth->password($this->data['User']['password_confirm'])) {
                echo "<script>alert('Las contraseñas no coinciden')</script>";
            } else {
                if ($this->User->saveAll($this->data)) {
                    $this->Session->setFlash("Usuario creado con exito");
                    $this->redirect(array("controller" => 'users', 'action' => 'list_users'));
                } else {
                    $this->Session->setFlash("Error guardando datos");
                    $this->set('branches', $this->User->Branch->find('list', array('order' => 'nombre ASC', 'fields' => array('id', 'nombre'))));
                    $this->set('groups', $this->User->Group->find('list', array('conditions' => array('Group.id NOT' => array(1, 7)), 'order' => 'name ASC', 'fields' => array('id', 'name'))));
                }
            }
        } else {
            if ($this->Auth->user('group_id') == 28) {
                $this->set('branches', $this->User->Branch->find('list', array('order' => 'nombre ASC', 'fields' => array('id', 'nombre'))));
                $this->set('groups', $this->User->Group->find('list', array('conditions' => array('Group.id' => array(15, 24, 29)), 'order' => 'name ASC', 'fields' => array('id', 'name'))));
            } else {
                $this->set('branches', $this->User->Branch->find('list', array('order' => 'nombre ASC', 'fields' => array('id', 'nombre'))));
                $this->set('groups', $this->User->Group->find('list', array('conditions' => array('Group.id NOT' => array(1, 7)), 'order' => 'name ASC', 'fields' => array('id', 'name'))));
            }
        }
    }

    function list_users() {
        $this->User->recursive = -1;

        if ($this->Auth->user('group_id') == 28) {
            $this->set('User', $this->User->find('all', array(
                        'conditions' => array('User.branch_id' => 39)
                    )));
        } else {

            $this->set('User', $this->User->find('all', array('conditions' =>
                        array(
                            "NOT" => array("User.group_id" => array(1, 7))
                        )
                    )));
        }
    }

    function edit($id = null) {
        if (empty($this->data)) {
            if ($this->Auth->user('group_id') == 28) {
                $this->data = $this->User->find("first", array("conditions" => array("User.id" => $id)));
                $this->set('groups', $this->User->Group->find('list', array('conditions' => array('Group.id' => array(15, 24, 29)), 'order' => 'name ASC', 'fields' => array('id', 'name'))));
                $this->set('branches', $this->User->Branch->find('list', array('order' => 'nombre ASC', 'fields' => array('id', 'nombre'))));
            } else {
                $this->data = $this->User->find("first", array("conditions" => array("User.id" => $id)));
                $this->set('groups', $this->User->Group->find('list', array('conditions' => array('Group.id NOT' => array(1, 7)), 'order' => 'name ASC', 'fields' => array('id', 'name'))));
                $this->set('branches', $this->User->Branch->find('list', array('order' => 'nombre ASC', 'fields' => array('id', 'nombre'))));
            }
        } else {
            if ($this->User->save($this->data)) {
                $this->Session->setFlash("Usuario editado con exito");
                $this->redirect(array('controller' => 'users', 'action' => "list_users"));
            } else {
                $this->Session->setFlash("Error Guardando Datos");
                $this->set('groups', $this->User->Group->find('list', array('conditions' => array('Group.id NOT' => array(1, 7)), 'order' => 'name ASC', 'fields' => array('id', 'name'))));
                $this->set('branches', $this->User->Branch->find('list', array('order' => 'nombre ASC', 'fields' => array('id', 'nombre'))));
            }
        }
    }

    function delete($id) {

        if ($this->User->delete($id)) {
            $this->Session->setFlash('Usuario Borrado con exito');
            $this->redirect(array('controller' => 'Users', 'action' => 'list_users'));
        }
    }

}

?>
